<!DOCTYPE html>
<html lang="zh-CN">





<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/apple-touch-icon.png">
  <link rel="icon" type="image/png" href="/blog/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="兴趣使然的个人博客">
  <meta name="author" content="Ilirus">
  <meta name="keywords" content>
  <title>使用ControllerAdvice统一封装Controller返回数据 - Ilirus</title>

  <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css">


  <link rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css">
  <link rel="stylesheet" href="/blog/lib/hint/hint.min.css">

  
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/atom-one-light.min.css">
  

  


<!-- 主题依赖的图标库，不要自行修改 -->
<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">

<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">

<link rel="stylesheet" href="/blog/css/main.css">

<!-- 自定义样式保持在最底部 -->


  <script src="/blog/js/utils.js"></script>
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/blog/">&nbsp;<strong>Ilirus</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/blog/img/202012/title.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2021-01-10 08:02">
      2021年1月10日 早上
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      724 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      10
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
            <article class="markdown-body">
              <p>在给前端提供Api接口时，通常会约定好一个统一返回格式，这样方便前端处理返回结果</p>
<pre><code class="hljs java"><span class="hljs-meta">@RestController</span>
<span class="hljs-meta">@RequestMapping</span>(<span class="hljs-string">"/index"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IndexController</span> </span>&#123;

  <span class="hljs-meta">@GetMapping</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> R&lt;Data&gt; <span class="hljs-title">index</span><span class="hljs-params">()</span> </span>&#123;
    <span class="hljs-keyword">return</span> R.ofSuccess(<span class="hljs-keyword">new</span> Data());
  &#125;
&#125;</code></pre>
<p>但每次都要用统一返回类手动封装一次再返回还是比较麻烦的，可以使用<code>@ControllerAdvice</code> 注解来进行统一封装，避免每次手动封装</p>
<p><strong>定义ControllerAdvice</strong></p>
<pre><code class="hljs java"><span class="hljs-comment">// 这里的annotations = ApiResult.class 代表只有在类上有@ApiResult 注解的Controller 才会被处理</span>
<span class="hljs-comment">// 如果不写则默认对所有Controller 进行处理</span>
<span class="hljs-meta">@RestControllerAdvice</span>(annotations = ApiResult<span class="hljs-class">.<span class="hljs-keyword">class</span>)
<span class="hljs-title">public</span> <span class="hljs-title">class</span> <span class="hljs-title">ResponseAdvice</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">ResponseBodyAdvice</span>&lt;<span class="hljs-title">Object</span>&gt; </span>&#123;
  <span class="hljs-meta">@Override</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">supports</span><span class="hljs-params">(MethodParameter returnType, Class&lt;? extends HttpMessageConverter&lt;?&gt;&gt; converterType)</span> </span>&#123;
    <span class="hljs-comment">// 判断返回类型是否已经是定义好的统一返回类型, 以及@ApiResult 注解是否启用</span>
    <span class="hljs-comment">// 返回true 则表示进入下一步处理, 返回false 则表示不做处理, 原样返回</span>
    <span class="hljs-keyword">return</span> !returnType.getParameterType().isAssignableFrom(R<span class="hljs-class">.<span class="hljs-keyword">class</span>)&amp;&amp;
            !<span class="hljs-title">returnType</span>.<span class="hljs-title">hasMethodAnnotation</span>(<span class="hljs-title">ApiResult</span>.<span class="hljs-title">Disable</span>.<span class="hljs-title">class</span>)</span>;
  &#125;

  <span class="hljs-meta">@Override</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">beforeBodyWrite</span><span class="hljs-params">(Object body, MethodParameter returnType, MediaType selectedContentType, Class&lt;? extends HttpMessageConverter&lt;?&gt;&gt; selectedConverterType, ServerHttpRequest request, ServerHttpResponse response)</span> </span>&#123;

    <span class="hljs-keyword">return</span> R.ofSuccess(body);
  &#125;
&#125;</code></pre>
<a id="more"></a>
<p><strong>定义注解</strong><br><pre><code class="hljs java"><span class="hljs-meta">@Target</span>(ElementType.TYPE)
<span class="hljs-meta">@Retention</span>(RetentionPolicy.RUNTIME)
<span class="hljs-meta">@Documented</span>
<span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> ApiResult &#123;

    <span class="hljs-meta">@Target</span>(ElementType.METHOD)
    <span class="hljs-meta">@Retention</span>(RetentionPolicy.RUNTIME)
    <span class="hljs-meta">@Documented</span>
    <span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> Disable &#123;&#125;
&#125;</code></pre></p>
<p><strong>使用</strong><br><pre><code class="hljs java"><span class="hljs-meta">@RestController</span>
<span class="hljs-meta">@RequestMapping</span>(<span class="hljs-string">"/index"</span>)
<span class="hljs-meta">@ApiResult</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IndexController</span> </span>&#123;

  <span class="hljs-meta">@GetMapping</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> Data <span class="hljs-title">index</span><span class="hljs-params">()</span> </span>&#123;
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Data();
  &#125;

  <span class="hljs-meta">@GetMapping</span>(<span class="hljs-string">"/string"</span>)
  <span class="hljs-comment">// 不做处理直接返回</span>
  <span class="hljs-meta">@ApiResult</span>.<span class="hljs-function">Disable
  <span class="hljs-keyword">public</span> String <span class="hljs-title">returnStr</span><span class="hljs-params">()</span> </span>&#123;
    <span class="hljs-keyword">return</span> <span class="hljs-string">"success"</span>;
  &#125;
&#125;</code></pre></p>
<p>顺嘴提一句, 使用组合注解也是可以的<br><pre><code class="hljs java"><span class="hljs-meta">@Target</span>(ElementType.TYPE)
<span class="hljs-meta">@Retention</span>(RetentionPolicy.RUNTIME)
<span class="hljs-meta">@Documented</span>
<span class="hljs-meta">@ApiResult</span>
<span class="hljs-meta">@WithExceptionHandler</span>
<span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> ApiResultWithExceptionHandler &#123;
&#125;</code></pre></p>
<pre><code class="hljs java"><span class="hljs-meta">@RestController</span>
<span class="hljs-meta">@RequestMapping</span>(<span class="hljs-string">"/index"</span>)
<span class="hljs-meta">@ApiResultWithExceptionHandler</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IndexController</span> </span>&#123;

  <span class="hljs-meta">@GetMapping</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> Data <span class="hljs-title">index</span><span class="hljs-params">()</span> </span>&#123;
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Data();
  &#125;
&#125;</code></pre>
<p><img src="https://erina.gitee.io/blog/img/202012/01.png" srcset="/blog/img/loading.gif" alt="01"></p>
<p>等会，还没完，转换其他类型的时候都是正常的，但是如果遇到String类型，就会报错 <code>R cannot be cast to class String</code></p>
<p>这是因为在<code>Controller</code> 返回<code>String</code> 类型时，<code>Spring</code> 会优先使用<code>StringHttpMessageConverter</code>来进行转换处理，而我们又在统一处理器里面把类型更换为了自定义的统一返回类，所以会导致转换出错</p>
<p>解决的办法有三种</p>
<p>第一种: 在处理器中做判断, 为<code>String</code> 的时候手动格式化为统一返回类对应的<code>Json</code>格式字符串<br><pre><code class="hljs java"><span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">beforeBodyWrite</span><span class="hljs-params">(Object body, MethodParameter returnType, MediaType selectedContentType, Class&lt;? extends HttpMessageConverter&lt;?&gt;&gt; selectedConverterType, ServerHttpRequest request, ServerHttpResponse response)</span> </span>&#123;

  <span class="hljs-comment">// 判断Controller的返回类型是否是String 类型, 如果是, 则转换为Json格式的String再返回</span>
  <span class="hljs-keyword">if</span>(returnType.getParameterType().isAssignableFrom(String<span class="hljs-class">.<span class="hljs-keyword">class</span>)) </span>&#123;
    <span class="hljs-keyword">return</span> R.ofSuccess(body).toJsonString();
  &#125;

  <span class="hljs-keyword">return</span> R.ofSuccess(body);
&#125;</code></pre></p>
<p>第二、三种: 更改<code>Spring</code> 的<code>HttpMessageConverter</code> 配置，使其用对应的<code>HttpMessageConverter</code> 来进行转换<br><pre><code class="hljs java"><span class="hljs-meta">@Component</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WebConfiguration</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">WebMvcConfigurer</span> </span>&#123;
  <span class="hljs-meta">@Override</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">configureMessageConverters</span><span class="hljs-params">(List&lt;HttpMessageConverter&lt;?&gt;&gt; converters)</span> </span>&#123;
    <span class="hljs-comment">// 第二种: 将json 处理的转换器放到第一位, 使得json 转换器优先处理返回值</span>
    <span class="hljs-comment">// converters.add(0, new MappingJackson2HttpMessageConverter());</span>
    <span class="hljs-comment">// 第三种: 去掉String类型的转换器, 不使用String类型的转换器</span>
    <span class="hljs-comment">// converters.removeIf(converter -&gt; converter.getClass().isAssignableFrom(StringHttpMessageConverter.class));</span>
  &#125;
&#125;</code></pre></p>
<p><img src="https://erina.gitee.io/blog/img/202012/02.png" srcset="/blog/img/loading.gif" alt="02"></p>
<p>到此为止才算完成了</p>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/blog/categories/Java/">Java</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/blog/tags/Java/">Java</a>
                    
                      <a class="hover-with-bg" href="/blog/tags/SpringBoot/">SpringBoot</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://zh.wikipedia.org/wiki/Wikipedia:CC_BY-SA_3.0%E5%8D%8F%E8%AE%AE%E6%96%87%E6%9C%AC" rel="nofollow noopener">CC BY-SA 3.0协议</a> 。转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/blog/2021/05/20/Minecraft-Mod开发手册00-开发环境搭建/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Minecraft Mod 开发手册00: 开发环境搭建</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/blog/2020/11/18/Validate自定义校验注解/">
                        <span class="hidden-mobile">Validate自定义校验注解</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                
  <div id="lv-container" data-id="city" data-uid="MTAyMC80NTMxNi8yMTgyOQ==">
    <script type="text/javascript">
      function loadLivere() {
        addScript('https://cdn-city.livere.com/js/embed.dist.js');
      }
      createObserver(loadLivere, 'lv-container');
    </script>
    <noscript>为正常使用来必力评论功能请允许 JavaScript 运行</noscript>
  </div>


              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    

    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/debouncer.js" ></script>
<script  src="/blog/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/blog/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/blog/js/clipboard-use.js" ></script>







  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "使用ControllerAdvice统一封装Controller返回数据&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/blog/js/local-search.js" ></script>
  <script>
    var path = "/blog/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script type="text/javascript">
      //定义获取词语下标
      var a_idx = 0;
      jQuery(document).ready(function ($) {
        //点击body时触发事件
        $("body").click(function (e) {
          //需要显示的词语
          var a = new Array("富强", "民主", "文明", "和谐", "自由", "平等", "公正", "法治", "爱国", "敬业", "诚信", "友善");
          //设置词语给span标签
          var $i = $("<span/>").text(a[a_idx]);
          //下标等于原来下标+1  余 词语总数
          a_idx = (a_idx + 1) % a.length;
          //获取鼠标指针的位置，分别相对于文档的左和右边缘。
          //获取x和y的指针坐标
          var x = e.pageX, y = e.pageY;
          //在鼠标的指针的位置给$i定义的span标签添加css样式
          $i.css({
            "z-index": 999,
            "top": y - 20,
            "left": x,
            "position": "absolute",
            "font-weight": "bold",
            "color": rand_color()
          });
          // 随机颜色
          function rand_color() {
            return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
          }
          //在body添加这个标签
          $("body").append($i);
          //animate() 方法执行 CSS 属性集的自定义动画。
          //该方法通过CSS样式将元素从一个状态改变为另一个状态。CSS属性值是逐渐改变的，这样就可以创建动画效果。
          //详情请看http://www.w3school.com.cn/jquery/effect_animate.asp
          $i.animate({
            //将原来的位置向上移动180
            "top": y - 180,
            "opacity": 0
            //1500动画的速度
          }, 1500, function () {
            //时间到了自动删除
            $i.remove();
          });
        });
      })
      ;
    </script>
  














<script src="/blog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginModelPath":"assets/","model":{"jsonPath":"/blog/live2dw/assets/tororo.model.json"},"display":{"position":"left","width":300,"height":300},"mobile":{"show":false},"log":false,"pluginJsPath":"lib/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
